/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gw2lol;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.net.URLConnection;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 *
 * @author Alex
 */
public class Gw2ApiInterface {

    public static ArrayList<ArrayList<DataSet>> loadEventNames() {

        return loadMULTC("event_names.json");
    }

    public static ArrayList<ArrayList<DataSet>> loadMapNames() {

        return loadMULTC("map_names.json");
    }
    
    public static ArrayList<ArrayList<DataSet>> loadEvents(String worldId) {

        return load("events.json?world_id=" + worldId);
    }
    /**
     * @param args the command line arguments
     */
    public static ArrayList<ArrayList<DataSet>> load(String commands) {

        TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(
                        java.security.cert.X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(
                        java.security.cert.X509Certificate[] certs, String authType) {
                }
            }
        };

// Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
        }

// Now you can access an https URL without having the certificate in the truststore


        URL url;
        InputStream is = null;
        BufferedReader br;
        String line;
        ArrayList<String> result = new ArrayList<String>();

        String urlBase = "https://api.guildwars2.com/v1/";
        urlBase = urlBase + commands;

        System.out.println(urlBase);
        try {

            url = new URL(urlBase);
            URLConnection yc = url.openConnection();
            is = url.openStream();  // throws an IOException
            br = new BufferedReader(
                    new InputStreamReader(
                    yc.getInputStream()));

            while ((line = br.readLine()) != null) {
                result.add(line);
            }
        } catch (MalformedURLException mue) {
            mue.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException ioe) {
                // nothing to see here
            }
        }

        return interp(result);
    }

    public static ArrayList<ArrayList<DataSet>> interp(ArrayList<String> result) {

        int start = -1;
        int end = -1;
        for (int i = 0; i < result.get(0).length(); i++) {
            if ("[".equals(result.get(0).substring(i, i + 1))) {
                start = i;
            }

        }

        if (start >= 0) {
            result.set(0, result.get(0).substring(start + 1));
        }

        for (int i = result.get(result.size() - 1).length() - 1; i > 0; i--) {
            if ("]".equals(result.get(result.size() - 1).substring(i, i + 1))) {
                end = i;
            }

        }

        if (end >= 0) {
            result.set((result.size() - 1), result.get((result.size() - 1)).substring(0, end));

        }

        ArrayList<ArrayList<DataSet>> finalVal = new ArrayList<ArrayList<DataSet>>();

        for (int i = 0; i < result.size(); i++) {
            ArrayList<DataSet> thisRes = new ArrayList<DataSet>();

            //Probably I don't need this, but CBF to not do it here and then it fking something else up
            result.get(i).replaceAll("\\{", "");
            result.get(i).replaceAll("\\}", "");

            String[] token = result.get(i).split(",");
            for (int j = 0; j < token.length; j++) {
                String[] theSplit = token[j].split(":");
                DataSet thisOne = new DataSet(theSplit[0], theSplit[1]);
                thisRes.add(thisOne);
            }

            finalVal.add(thisRes);
        }


        return finalVal;
    }

    public static ArrayList<ArrayList<DataSet>> loadMULTC(String commands) {


        TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(
                        java.security.cert.X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(
                        java.security.cert.X509Certificate[] certs, String authType) {
                }
            }
        };

// Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
        }

// Now you can access an https URL without having the certificate in the truststore


        URL url;
        InputStream is = null;
        BufferedReader br;
        String line;
        ArrayList<String> result = new ArrayList<String>();

        String urlBase = "https://api.guildwars2.com/v1/";
        urlBase = urlBase + commands;

        System.out.println(urlBase);
        try {

            url = new URL(urlBase);
            URLConnection yc = url.openConnection();
            is = url.openStream();  // throws an IOException
            br = new BufferedReader(
                    new InputStreamReader(
                    yc.getInputStream()));

            while ((line = br.readLine()) != null) {
                result.add(line);
            }
        } catch (MalformedURLException mue) {
            mue.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException ioe) {
                // nothing to see here
            }
        }

        return interpMC(result);
    }

    public static ArrayList<ArrayList<DataSet>> interpMC(ArrayList<String> result) {

        int start = -1;
        int end = -1;
        for (int i = 0; i < result.get(0).length(); i++) {
            if ("[".equals(result.get(0).substring(i, i + 1))) {
                start = i;
            }

        }

        if (start >= 0) {
            result.set(0, result.get(0).substring(start + 1));
        }

        for (int i = result.get(result.size() - 1).length() - 1; i > 0; i--) {
            if ("]".equals(result.get(result.size() - 1).substring(i, i + 1))) {
                end = i;
            }

        }

        if (end >= 0) {
            result.set((result.size() - 1), result.get((result.size() - 1)).substring(0, end));

        }

        ArrayList<ArrayList<DataSet>> finalVal = new ArrayList<ArrayList<DataSet>>();

        for (int i = 0; i < result.size(); i++) {
            ArrayList<DataSet> thisRes = new ArrayList<DataSet>();
            
            //Probably I don't need this, but CBF to not do it here and then it fking something else up
            result.get(i).replaceAll("\\{", "");
            result.get(i).replaceAll("\\}", "");


            String[] token = result.get(i).split(",", 2);
            for (int j = 0; j < token.length; j++) {
                                System.out.print(token[j] + " vs -");
                String[] theSplit = token[j].split(":",2);
                System.out.println(theSplit[1]);
                DataSet thisOne = new DataSet(theSplit[0], theSplit[1]);
                thisRes.add(thisOne);

            }

            finalVal.add(thisRes);
        }


        return finalVal;
    }

    public static void main(String[] Args) {
        ArrayList<ArrayList<DataSet>> theText = load("world_names.json");

        for (int i = 0; i < theText.size(); i++) {
            for (int j = 0; j < theText.get(i).size(); j++) {
                System.out.print(theText.get(i).get(j).getVals() + "|");
            }
            System.out.println("");
        }



    }
}
